<script>
import { ref } from "vue";
import timestamp from "time-stamp";
import { logApi, phoneApi } from "../../api/index";
export default {
  setup() {
    let logs = ref([]);
    let phones = ref([]);
    let form = ref({});
    let columns = ref([
      {
        prop: "index",
        title: "序号",
      },
      {
        prop: "createTime",
        title: "时间",
      },
      {
        prop: "msg",
        title: "消息",
      },
      {
        prop: "phoneNumber",
        title: "手机号",
      },
      {
        prop: "battery",
        title: "电量",
      },
    ]);
    return {
      logs,
      phones,
      columns,
      form,
    };
  },
  async mounted() {
    this.getPhones();
    this.interval = setInterval(() => {
      this.search();
    }, 2000);
  },
  unmounted() {
    clearInterval(this.interval);
  },
  methods: {
    async getPhones() {
      try {
        const res = await phoneApi.get({});
        this.phones = res.data || [];
      } catch (e) {
        console.log(e);
      }
    },
    async search() {
      try {
        const searchData = new URLSearchParams(this.form).toString();
        const res = await logApi.get(searchData);
        this.logs = (res.data || []).map((item) => {
          return {
            ...item,
            createTime: item.createTime
              ? timestamp("YYYY-MM-DD HH:mm:ss", new Date(item.createTime))
              : "",
          };
        });
      } catch (e) {
        console.log(e);
      }
    },
  },
};
</script>

<template>
  <div class="sw_phone_container">
    <div class="flex">
      <div class="mr-10">
        <span>手机号：</span>
        <select name="phone" id="phone" v-model="form.phone">
          <option value="">请选择</option>
          <option
            v-for="phone in phones"
            :key="phone.phoneNumber"
            :value="phone.phoneNumber"
          >
            {{ phone.phoneNumber }}
          </option>
        </select>
      </div>
      <div class="mr-10">
        <span>消息:</span><input type="text" v-model="form.msg" />
      </div>
      <div>
        <button @click="search">查询</button>
      </div>
    </div>
    <table>
      <tr>
        <td v-for="(column, index) in columns" :key="index">
          {{ column.title }}
        </td>
      </tr>
      <tr v-for="(log, logIndex) in logs" :key="logIndex">
        <td v-for="(column, index) in columns" :key="index">
          <div v-if="column.prop == 'index'">
            <span>{{ logs.length - logIndex }}</span>
          </div>
          <div v-else>
            <span>
              {{ log[column.prop] }}
            </span>
          </div>
        </td>
      </tr>
    </table>
  </div>
</template>

<style lang="less">
.sw_phone_container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  flex-direction: column;
  .sw_mobile {
    font-size: 16px;
    padding: 15px 50px;
    border: 1px solid #ccc;
    border-radius: 5px;
    cursor: pointer;
  }
}
</style>
